package com.apes.scm.masterdata.product.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.OrientationDiagramMenu;
import com.apes.scm.masterdata.product.repository.OrientationDiagramCategoryRepository;
import com.apes.scm.masterdata.product.repository.OrientationDiagramMenuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("orientationDiagramMenuService")
public class OrientationDiagramMenuService extends DomainService {

    @Autowired
    private OrientationDiagramMenuRepository orientationDiagramMenuRepository;

    @Autowired
    private OrientationDiagramCategoryRepository orientationDiagramCategoryRepository;

    @Autowired
    private SequenceService sequenceService;
    /***
     * 创建
     */
    public OrientationDiagramMenu create(SimpleRequest request) {
        OrientationDiagramMenu menu = request.getO(OrientationDiagramMenu.class);

        if (menu.getId() == null || menu.getId() == 0){
            Integer id = Integer.valueOf(sequenceService.getId(OrientationDiagramMenu.CONST_TABLE_NAME));
            menu.setId(id);
        }

        // 设置树形图的路径，以及路径名
        menu.setPath(menu.localPath());
        menu.setPathName(menu.localPathName());
        return orientationDiagramMenuRepository.saveAndFlush(menu);
    }

    /***
     * 修改
     */
    public OrientationDiagramMenu update(SimpleRequest request) {
        OrientationDiagramMenu menu = request.getO(OrientationDiagramMenu.class);

        // 设置树形图的路径，以及路径名
        menu.setPath(menu.localPath());
        menu.setPathName(menu.localPathName());

        return orientationDiagramMenuRepository.saveAndFlush(menu);
    }


    /***
     * 删除
     */
    public String delete(SimpleRequest request) {
        OrientationDiagramMenu menu = request.getO(OrientationDiagramMenu.class);

        // 判断是否含有子节点
        List<OrientationDiagramMenu> children = orientationDiagramMenuRepository.findAll(JpaDsl.toCriteriaByEq(
                "parent.id", menu.getId()
        ));
        if (children.size() != 0) throw new RuntimeException("删除失败，当前目录含有子目录，无法删除");

        orientationDiagramMenuRepository.delete(menu);
        return "删除成功";
    }


    /***
     * 查找树形结构
     */
    public List<Map> findTreeData() {
        return orientationDiagramMenuRepository.findTreeData();
    }
}
